package myapp.com.phoneguard.adapter;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

import myapp.com.phoneguard.R;
import myapp.com.phoneguard.pojo.ContactModel;
import myapp.com.phoneguard.pojo.Info;

public class ContactsAdapter1 extends RecyclerView.Adapter<ContactsAdapter1.ContactsViewHolder> {

    private OnClickListener mOnClickListener;
    private List<ContactModel> contacts;
    private static final String TAG = "ContactsAdapter";

    public ContactsAdapter1(List<ContactModel> contacts,OnClickListener onClickListener) {
        this.contacts = contacts;
        mOnClickListener = onClickListener;
    }

    @Override
    public ContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.layaout_item_contacts, null);
        return new ContactsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ContactsViewHolder holder, int position) {
        final ContactModel contact = contacts.get(position);
        if (position == 0 || !contacts.get(position-1).getIndex().equals(contact.getIndex())){
            holder.tvIndex.setVisibility(View.VISIBLE);
            holder.tvIndex.setText(contact.getIndex());
        } else {
            holder.tvIndex.setVisibility(View.GONE);
        }
        holder.tvName.setText(contact.getName());
        holder.tvPhone.setText(contact.getPhonenumber());
        holder.lnContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = contact.getPhonenumber();
                if (!TextUtils.isEmpty(phone)) {
                    mOnClickListener.onClickContact(phone);
                }

            }
        });

    }


    @Override
    public int getItemCount() {
        return contacts.size();
    }

    class ContactsViewHolder extends RecyclerView.ViewHolder {
        TextView tvIndex;
        ImageView ivAvatar;
        TextView tvName;
        TextView tvPhone;
        LinearLayout lnContact;

        ContactsViewHolder(View itemView) {
            super(itemView);
            tvIndex = (TextView) itemView.findViewById(R.id.tv_index);
            ivAvatar = (ImageView) itemView.findViewById(R.id.iv_avatar);
            tvName = (TextView) itemView.findViewById(R.id.tv_name);
            tvPhone = (TextView) itemView.findViewById(R.id.tv_phone);
            lnContact = (LinearLayout) itemView.findViewById(R.id.layout_contact);
        }
    }

    public interface OnClickListener {

        void onClickContact(String phone);

    }
}

